import {DirectiveOptions} from "vue";

function addWaterMarker(str, parentNode, font, textColor, width = 400, height = 300) {
  // 水印文字，父元素，字体，文字颜色
  const canvas = document.createElement('canvas');
  parentNode.appendChild(canvas)
  canvas.width = width
  canvas.height = height
  canvas.style.display = 'none'
  const cvs = canvas.getContext('2d');
  if (cvs) {
    cvs.rotate((-20 * Math.PI) / 90)
    cvs.font = font || '16px Microsoft JhengHei'
    cvs.fillStyle = textColor || 'rgba(180, 180, 180, 0.3)'
    cvs.textAlign = 'left'
    cvs.textBaseline = 'middle'
    cvs.fillText(str, canvas.width / 10, canvas.height / 2)
    parentNode.style.backgroundImage = 'url(' + canvas.toDataURL('image/png') + ')'
  }
  canvas.remove()
}

const waterMarker: DirectiveOptions = {
  bind: function (el, binding) {
    addWaterMarker(binding.value.text, el, binding.value.font, binding.value.textColor,binding.value.width,binding.value.height)
  },
  update(el,binding) {
    addWaterMarker(binding.value.text, el, binding.value.font, binding.value.textColor,binding.value.width,binding.value.height)
  }
}

export default waterMarker
